package bit2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class bitMain25 {
    public static void main(String[] args) throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要扫描的根目录：");
        String rootDir=scanner.next();
        File rootFile=new File(rootDir);
        if (!rootFile.isDirectory()){
            System.out.println("该目录不存在或者不是文件！直接退出.  ");
            return;
        }
        System.out.println("请输入要查询的词：");
        String query=scanner.next();
        List<File> results=new ArrayList<>();
        scanDirWithContent(rootFile,query,results);
        for (File file:results) {
            System.out.println(file.toString());
        }
    }
    public static void  scanDirWithContent(File rootFile,String query,List<File> results){
        File[] files=rootFile.listFiles();
        if (files==null||files.length==0){
            return;
        }
        for (File f:files) {
            if (f.isDirectory()){
                scanDirWithContent(f,query,results);
            }else {
                if (isContentContains(f,query)||f.getName().contains(query)){
                    results.add(f);
                }
            }
        }
    }
    public static boolean isContentContains(File rootFile,String query){
        StringBuilder stringBuilder=new StringBuilder();
        try(InputStream inputStream=new FileInputStream(rootFile)){
            Scanner scanner=new Scanner(inputStream,"UTF-8");
            while (scanner.hasNextLine()){
                String line=scanner.nextLine();
                stringBuilder.append(line+"\n");
            }
        }catch (IOException e){
            e.printStackTrace();
        }return stringBuilder.indexOf(query)!=-1;
    }
}
